import 'dart:convert';

import 'package:amway_superapp_creator_plugin/analysis/zhuge_circle.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/dialog/comm_tip_dialog.dart';
import 'package:amway_superapp_creator_plugin/dialog/loading_dialog.dart';
import 'package:amway_superapp_creator_plugin/models/circle_detail_model.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/utils/oss_util.dart';
import 'package:amway_superapp_creator_plugin/utils/sp_util.dart';
import 'package:amway_superapp_creator_plugin/utils/time_util.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/circle/my_circle_details_model.dart';
import 'package:amway_superapp_creator_plugin/views/base_view.dart';
import 'package:amway_superapp_creator_plugin/widget/expandable_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:page_view_indicators/circle_page_indicator.dart';
import 'package:provider/provider.dart';

import '../../view_state.dart';
import 'send_editer_page_view.dart';

class MyCircleDetailsImages extends StatelessWidget {
  String id;

  MyCircleDetailsImages(this.id);

  @override
  Widget build(BuildContext context) {
    return BaseView(
        model: MyCircleDetailsModel(api: Provider.of(context)),
        onModelReady: (model) {
          model.getCircleDetail(id);
        },
        builder: (context, model, child) => Scaffold(
              appBar: AppBar(
                elevation: 0,
                brightness: Brightness.light,
                backgroundColor: Colors.white,
                leading: IconButton(
                  icon: Image.asset(
                    'picture/icon_back.png',
                    package: 'amway_superapp_creator_plugin',
                  ),
                  onPressed: () {
                    Application.router.pop(context);
                  },
                ),
                title: Text(
                  '我的圈子',
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(18),
                      color: ColorsConfig.c_2c2c2c),
                ),
                centerTitle: true,
              ),
              body: _buildBody(context, model),
              bottomNavigationBar: _bottomBar(model, context),
            ));
  }

  Widget _bottomBar(MyCircleDetailsModel model, BuildContext context) {
    return model.circleDetail != null && model.circleDetail.officialFlag == "NO"
        ? Container(
            alignment: Alignment.topCenter,
            decoration: BoxDecoration(color: Colors.white, boxShadow: [
              BoxShadow(
                  color: ColorsConfig.c_26000000,
                  offset: Offset(0.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 15.0, //阴影模糊程度
                  spreadRadius: 0.0 //阴影扩散程度
                  )
            ]),
            height: ScreenUtil().setWidth(90),
            padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(15),
                right: ScreenUtil().setWidth(15),
                top: ScreenUtil().setWidth(10)),
            child: model.circleDetail.auditStatus == "UN_PASS"
                ? Container(
                    height: ScreenUtil().setWidth(50),
                    decoration: BoxDecoration(
                      color: ColorsConfig.c_396E75,
                      borderRadius: BorderRadius.circular(25),
                    ),
                    child: InkWell(
                      onTap: () {
                        ZhugeCircleAnalysis.circleDetailsEditer("我的圈子");
                        SpUtil.setData(
                            "${SpUtil.local_circle_data}${model.circleDetail.ada}",
                            json.encode(model.circleDetail));
                        Navigator.of(context)
                            .pushReplacement(new MaterialPageRoute(
                                builder: (context) => new SendEditerPageView(
                                      isNewAdd: false,
                                      circleState: 1,
                                      isUserDraft: false,
                                      circleData: model.circleDetail,
                                      amwayId: model.circleDetail.amwayId,
                                      amwayAda: model.circleDetail.ada,
                                    )));
                      },
                      child: Container(
                        width: double.infinity,
                        alignment: Alignment.center,
                        child: Text(
                          "编辑",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: ScreenUtil().setSp(18)),
                        ),
                      ),
                    ),
                  )
                : Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                        Container(
                            width: ScreenUtil().setWidth(165),
                            child: MaterialButton(
                              elevation: 0,
                              color: Colors.white,
                              onPressed: () {
                                if (model.circleDetail.publishStatus ==
                                    "UN_PUBLISH") {
                                  //未发布
                                  SpUtil.setData(
                                      "${SpUtil.local_circle_data}${model.circleDetail.ada}",
                                      json.encode(model.circleDetail));
                                  Navigator.of(context).pushReplacement(
                                      new MaterialPageRoute(
                                          builder: (context) =>
                                              new SendEditerPageView(
                                                  isNewAdd: false,
                                                  isUserDraft: false,
                                                  circleData:
                                                      model.circleDetail,
                                                  amwayId: model
                                                      .circleDetail.amwayId,
                                                  amwayAda:
                                                      model.circleDetail.ada,
                                                  circleState: 2)));
                                } else {
                                  ToastUtils.showShortToast("请先撤销发布后编辑内容");
                                }
                              },
                              child: Text(
                                "编辑",
                                style: TextStyle(
                                    color: model.circleDetail.publishStatus ==
                                            "UN_PUBLISH"
                                        ? ColorsConfig.c_396E75
                                        : ColorsConfig.c_4d396E75,
                                    fontSize: ScreenUtil().setSp(18)),
                              ),
                              height: ScreenUtil().setWidth(50),
                              shape: RoundedRectangleBorder(
                                  side: BorderSide(
                                      width: 1,
                                      color: model.circleDetail.publishStatus ==
                                              "UN_PUBLISH"
                                          ? ColorsConfig.c_396E75
                                          : ColorsConfig.c_4d396E75),
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(ScreenUtil().setWidth(25)),
                                  )),
                            )),
                        Container(
                          width: ScreenUtil().setWidth(165),
                          child: MaterialButton(
                            elevation: 0,
                            color: ColorsConfig.c_396E75,
                            onPressed: () {
                              if (model.circleDetail.publishStatus ==
                                  "UN_PUBLISH") {
                                ZhugeCircleAnalysis.circleDetailsSend("我的圈子");
                                //未发布
                                showDialog(
                                  context: context,
                                  builder: (ctx) {
                                    return LoadingDialog(
                                      canceledOnTouchOutside: false,
                                      tipMsg: '正在发布',
                                    );
                                  },
                                );
                                model.release(model.circleDetail.id,
                                    back: (result, msg) {
                                  Application.router.pop(context);
                                  if (result) {
                                    ZhugeCircleAnalysis.sendCircleResult(
                                        "我的圈子", true);
                                    ToastUtils.showShortToast("发布成功");
                                    Application.router.pop(context, "release");
                                  } else {
                                    ZhugeCircleAnalysis.sendCircleResult(
                                        "我的圈子", false);
                                    ToastUtils.showShortToast(msg);
                                  }
                                });
                              } else {
                                //已发布
                                showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (_) {
                                      return CommTipDialog(
                                        content: '确认撤销发布此圈子动态吗？',
                                        confirmText: "确认",
                                        confirmCallback: () {
                                          ZhugeCircleAnalysis
                                              .circleDetailsRevokeSend("我的圈子");
                                          showDialog(
                                            context: context,
                                            builder: (ctx) {
                                              return LoadingDialog(
                                                canceledOnTouchOutside: false,
                                                tipMsg: '正在撤销',
                                              );
                                            },
                                          );
                                          model.revokeRelease(
                                              model.circleDetail.id,
                                              back: (value) {
                                            Application.router.pop(context);
                                            if (value) {
                                              ToastUtils.showShortToast("撤销成功");
                                            } else {
                                              ToastUtils.showShortToast("撤销失败");
                                            }
                                          });
                                        },
                                        dismissCallback: () {},
                                      );
                                    });
                              }
                            },
                            child: Text(
                                model.circleDetail.publishStatus == "UN_PUBLISH"
                                    ? "发布"
                                    : "撤销发布",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil().setSp(18))),
                            height: ScreenUtil().setWidth(50),
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.all(
                              Radius.circular(ScreenUtil().setWidth(25)),
                            )),
                          ),
                        )
                      ]))
        : Container(
            height: 0,
          );
  }

  Widget _buildBody(BuildContext context, MyCircleDetailsModel model) {
    if (model.circleDetail == null) {
      return Container();
    }
    ZhugeCircleAnalysis.circleDetails(
        model.circleDetail.id, model.circleDetail.title);
    return model.state == ViewState.Busy
        ? Center(
            child: CircularProgressIndicator(),
          )
        : Container(
            child: SingleChildScrollView(
              child: Container(
                color: Colors.white,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildImagesView(context, model),
                    _buildCircleTitle(context, model),
                    _buildCircleContent(context, model),
                    _buildTextDate(context, model),
                    _buildShop(context, model),
                  ],
                ),
              ),
            ),
          );
  }

  Widget _buildImagesView(BuildContext context, MyCircleDetailsModel model) {
    return Container(
      width: double.infinity,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          AspectRatio(
            aspectRatio: 4 / 3,
            child: Container(
              height: ScreenUtil().setHeight(552),
              color: Colors.black,
              child: Stack(
                children: [
                  model.circleDetail != null &&
                          model.circleDetail.medias != null
                      ? Swiper(
                          onIndexChanged: (index) {
                            model.curIndex = index + 1;
                            _currentPageNotifier.value = index;
                          },
                          itemBuilder: (BuildContext context, int index) {
                            ZhugeCircleAnalysis.circleDetailsPagLoadFinsh(
                                states(
                                    model.circleDetail.displayAudits,
                                    model.circleDetail.medias[index].data,
                                    model));
                            return Stack(
                              fit: StackFit.expand,
                              children: [
                                Image.network(
                                  model.circleDetail.medias[index].data,
                                ),
                                _verify(
                                    model.circleDetail.displayAudits,
                                    model.circleDetail.medias[index].data,
                                    model)
                              ],
                            );
                          },
                          itemCount: model.circleDetail.medias.length > 1
                              ? model.circleDetail.medias.length
                              : 1,
                          loop: model.circleDetail.medias.length > 1
                              ? true
                              : false,
                        )
                      : Image.network(
                          "http://via.placeholder.com/414x552",
                          fit: BoxFit.fill,
                        ),
                  model.circleDetail.medias != null &&
                          model.circleDetail.medias.length > 1
                      ? Align(
                          alignment: Alignment.bottomRight,
                          child: Container(
                            padding: EdgeInsets.only(
                                right: ScreenUtil().setWidth(10),
                                bottom: ScreenUtil().setHeight(10)),
                            child: Text(
                              "${model.curIndex}/${model.circleDetail.medias.length}",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenUtil().setSp(12)),
                            ),
                          ),
                        )
                      : Container()
                ],
              ),
            ),
          ),
          _buildPageViewIndicator(context, model),
        ],
      ),
    );
  }

  final _currentPageNotifier = ValueNotifier<int>(0);

  //指示器
  Widget _buildPageViewIndicator(
      BuildContext context, MyCircleDetailsModel model) {
    return model.circleDetail != null && model.circleDetail.medias != null
        ? Container(
            width: double.infinity,
            color: Colors.white,
            padding: EdgeInsets.only(
                top: ScreenUtil().setHeight(12),
                bottom: ScreenUtil().setHeight(12)),
            child: CirclePageIndicator(
              currentPageNotifier: _currentPageNotifier,
              itemCount: model.circleDetail.medias.length > 1
                  ? model.circleDetail.medias.length
                  : 0,
            ))
        : Container();
  }

  Widget _buildCircleTitle(BuildContext context, MyCircleDetailsModel model) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(16),
          right: ScreenUtil().setWidth(16),
          top: ScreenUtil().setHeight(18),
          bottom: ScreenUtil().setHeight(24)),
      child: Stack(
        alignment: Alignment.centerRight,
        children: [
          Container(
              width: double.infinity,
              child: Text(
                model.circleDetail != null && model.circleDetail.title != null
                    ? "${model.circleDetail.title}"
                    : "",
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: Colors.black, fontSize: ScreenUtil().setSp(22)),
              )),
          Container(
            width: ScreenUtil().setWidth(100),
            height: ScreenUtil().setWidth(25),
            alignment: Alignment.centerRight,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.white,
                  ColorsConfig.c_0fffffff,
                ],
              ),
            ),
            child: Container(
              color: Colors.white,
              child: _verify(
                  model.circleDetail.displayAudits,
                  model.circleDetail != null && model.circleDetail.title != null
                      ? model.circleDetail.title
                      : "",
                  model),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildCircleContent(BuildContext context, MyCircleDetailsModel model) {
    return Container(
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(16), right: ScreenUtil().setWidth(16)),
      child: states(
                      model.circleDetail.displayAudits,
                      model.circleDetail != null &&
                              model.circleDetail.description != null
                          ? model.circleDetail.description
                          : "",
                      model) ==
                  3 ||
              states(
                      model.circleDetail.displayAudits,
                      model.circleDetail != null &&
                              model.circleDetail.description != null
                          ? model.circleDetail.description
                          : "",
                      model) ==
                  1
          ? Stack(
              alignment: AlignmentDirectional.bottomEnd,
              children: [
                ExpandableText(
                  text: model.circleDetail != null &&
                          model.circleDetail.description != null
                      ? model.circleDetail.description
                      : "",
                  isShow: false,
                  maxLines: 10,
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(14), color: Colors.black),
                  expand: false,
                ),
                Container(
                  alignment: Alignment.bottomRight,
                  width: ScreenUtil().setWidth(110),
                  height: ScreenUtil().setWidth(25),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        Colors.white,
                        ColorsConfig.c_0fffffff,
                      ],
                    ),
                  ),
                  child: Container(
                    color: Colors.white,
                    child: _verify(
                        model.circleDetail.displayAudits,
                        model.circleDetail != null &&
                                model.circleDetail.description != null
                            ? model.circleDetail.description
                            : "",
                        model),
                  ),
                )
              ],
            )
          : ExpandableText(
              text: model.circleDetail != null &&
                      model.circleDetail.description != null
                  ? model.circleDetail.description
                  : "",
              isShow: true,
              maxLines: 10,
              style: TextStyle(
                  fontSize: ScreenUtil().setSp(14), color: Colors.black),
              expand: false,
            ),
    );
  }

  Widget _buildTextDate(BuildContext context, MyCircleDetailsModel model) {
    return Container(
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(16),
          top: ScreenUtil().setHeight(18),
          bottom: ScreenUtil().setHeight(34)),
      child: Text(
        model.circleDetail != null && model.circleDetail.createTime != null
            ? TimeUtil.formatTime(model.circleDetail.createTime)
            : "",
        style: TextStyle(
            fontSize: ScreenUtil().setSp(14), color: ColorsConfig.c_802c2c2c),
      ),
    );
  }

  Widget _verify(List<DisplayAudits> displayAudits, String data,
      MyCircleDetailsModel model) {
    return Container(
        child: states(displayAudits, data, model) == 1
            ? Image.asset(
                "picture/icon_under_review.png",
                package: 'amway_superapp_creator_plugin',
                width: ScreenUtil().setWidth(80),
                height: ScreenUtil().setWidth(30),
              )
            : states(displayAudits, data, model) == 3
                ? Image.asset(
                    "picture/icon_audit_nopass.png",
                    package: 'amway_superapp_creator_plugin',
                    width: ScreenUtil().setWidth(80),
                    height: ScreenUtil().setWidth(30),
                  )
                : Text(""));
  }

  int states(List<DisplayAudits> displayAudits, String data,
      MyCircleDetailsModel model) {
    int s = 0;
    if (displayAudits != null)
      displayAudits.forEach((element) {
        if (data == element.data) {
          if (element.propertyNameTip == "CIRCLE_MEDIAS") {
            s = state(element.status);
            model.circleDetail.medias.forEach((d) {
              if (d.data == element.data) {
                d.state = s;
              }
            });
            return s;
          }
          if (element.propertyNameTip == "CIRCLE_TITLE") {
            s = state(element.status);
            model.circleDetail.titleVerify = s;
            return s;
          } else if (element.propertyNameTip == "CIRCLE_DESCRIPTION") {
            s = state(element.status);
            model.circleDetail.descriptionVerify = s;
            return s;
          }
        }
      });
    return s;
  }

  int state(String status) {
    switch (status) {
      case "AUDITING": //审核中
        return 1;
        break;
      case "PASSED": //通过
        return 2;
        break;
      case "UN_PASS": //不通过
        return 3;
        break;
      default:
        return 4;
        break;
    }
  }

/*
* 商品
* */
  _buildShop(BuildContext context, MyCircleDetailsModel model) {
    if (model.circleDetail.products != null &&
        model.circleDetail.products.length > 0) {
      return Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius:
                  BorderRadius.all(Radius.circular(ScreenUtil().setWidth(12))),
              boxShadow: [
                BoxShadow(
                    color: ColorsConfig.c_1a000000,
                    offset: Offset(0.0, 0.0), //阴影xy轴偏移量
                    blurRadius: 21.0, //阴影模糊程度
                    spreadRadius: 0.0 //阴影扩散程度
                    )
              ]),
          margin: EdgeInsets.only(
              left: ScreenUtil().setWidth(15),
              right: ScreenUtil().setWidth(15),
              bottom: ScreenUtil().setHeight(15)),
          child: _shop(model, context));
    } else {
      return Container();
    }
  }

  Widget _shop(MyCircleDetailsModel provide, BuildContext context) {
    return ListView.builder(
      physics: const NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      //自适应高度
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(15),
          right: ScreenUtil().setWidth(15),
          top: ScreenUtil().setWidth(5),
          bottom: ScreenUtil().setWidth(15)),
      itemCount: provide.circleDetail.products.length,
      itemBuilder: (context, index) {
        return _shopItem(provide, index, context);
      },
    );
  }

  Widget _shopItem(
      MyCircleDetailsModel provide, int index, BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10),
      height: ScreenUtil().setHeight(110),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
              margin: EdgeInsets.only(right: 12),
              child: Image.network(
                provide.circleDetail.products != null
                    ? "${OssHelper.pictureBaseUrl}${provide.circleDetail.products[index].picture}"
                    : "",
                width: ScreenUtil().setWidth(80),
                height: ScreenUtil().setWidth(80),
              )),
          Expanded(
              child: Column(
            children: [
              Expanded(
                  child: Container(
                alignment: Alignment.topLeft,
                child: Text(
                    provide.circleDetail.products != null &&
                            provide.circleDetail.products[index] != null &&
                            provide.circleDetail.products[index].productName !=
                                null
                        ? provide.circleDetail.products[index].productName
                        : "",
                    maxLines: 2,
                    style: TextStyle(
                        fontSize: ScreenUtil().setSp(16),
                        color: ColorsConfig.c_2c2c2c)),
              )),
              Container(
                  child: Row(
                children: [
                  Text("￥",
                      style: TextStyle(
                          color: ColorsConfig.c_cd0000,
                          fontSize: ScreenUtil().setSp(12))),
                  Expanded(
                      child: Text(
                          provide.circleDetail.products != null &&
                                  provide.circleDetail.products[index] !=
                                      null &&
                                  provide.circleDetail.products[index]
                                          .priceData !=
                                      null &&
                                  provide.circleDetail.products[index].priceData
                                          .price !=
                                      null
                              ? provide
                                  .circleDetail.products[index].priceData.price
                                  .toString()
                              : "",
                          style: TextStyle(
                              color: ColorsConfig.c_cd0000,
                              fontSize: ScreenUtil().setSp(16)))),
                ],
              ))
            ],
          )),
        ],
      ),
    );
  }
}
